package com.wutianyi.servlet.text;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.wltea.analyzer.IKSegmentation;
import org.wltea.analyzer.Lexeme;

import com.wutianyi.text.DictionaryServices;
import com.wutianyi.utils.NetUtils;

public class DictionaryServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2091564239398171295L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String words = NetUtils.getParameterString(req, "words", null);
		String type = NetUtils.getParameterString(req, "type", "split");
		System.out.println(words);
		PrintWriter pw = resp.getWriter();
		if (type.equals("split")) {
			pw = resp.getWriter();
			IKSegmentation ikSegment = new IKSegmentation(new StringReader(
					words));

			Lexeme lexeme = ikSegment.next();
			while (null != lexeme) {
				pw.println(lexeme.getLexemeText());

				lexeme = ikSegment.next();
			}
		} else if (type.equals("add")) {
			if (StringUtils.isBlank(words)) {
				pw.print(0);
			} else {
				String[] extWords = words.split("\n");
				List<String> ws = Arrays.asList(extWords);
				DictionaryServices.addExtendWords(ws);
				pw.print(1);
			}
		}

	}

}
